<?php
namespace plugins\logistics\controller;
use cmf\controller\PluginAdminBaseController;
use think\Db;
use think\Request;
use plugins\store\Common;
use plugins\logistics\interfaceLib\LogisticsOrder;
/**
 *
 */
class LogisticsOrderController extends PluginAdminBaseController
{
    private  $pageNum = "20";
    private  $com = '';
    private  $lm ='';
    protected function _initialize()
    {
        parent::_initialize();
        $adminId = cmf_get_current_admin_id();//获取后台管理员id，可判断是否登录
        if (!empty($adminId)) {
            $this->assign("admin_id", $adminId);
        }
        $this->com = new Common;


    }
    /**
     * 添加发货订单模拟数据
     */
    public function deliveryInfo( $data )
    {
        $Model = new plugins\logistics\model\LogisticsModel;
        $data = [          
            'order_num'  => 'order_5f2cf03402f0d',
            'store_id' => 'admin',
            'name' => '李四',
            'mobile' => '17761742332',
            'province' => '浙江省',
            'city' => '台州市',
            'area' => '椒江区',
            'address' => '君悦大厦',
            'remarks'=>'备注',
            'goods'=>'商品名称',
            'store_name'=>'店铺名称'
        ];
        $Model->deliveryInfo($data);
    }
    /**
     * 配置信息
     */
    public function logisticsConfig()
    {
        //店铺id
        $allow = $this->com->getAllowAccess();
        if($allow == 'true')$allow = 'admin';
        if($this->request->isPost()){
            $param = $this->request->post();
            $setting = [
                'code'=>['type'=>'require','message'=>['require'=>'物流公司必填']],
                'name'=>['type'=>'require','message'=>['require'=>'寄件人必填']],
                'mobile'=>['type'=>'require|number|max:11','message'=>['require'=>'手机号必填','number'=>'手机号需为数字','max'=>'号码需为11位']],
                'province_name'=>['type'=>'require','message'=>['require'=>'寄件地址必填']],
                'city_name'=>['type'=>'require','message'=>['require'=>'寄件地址必填']],
                'exp_area_name'=>['type'=>'require','message'=>['require'=>'寄件地址必填']],
                'address'=>['type'=>'require','message'=>['require'=>'寄件地址必填']]
            ];
            // 验证参数
            checkParam($setting,$param);
            if(db('logistics_sender')->where('store_id',$allow)->find()){
                $data = db('logistics_sender')->where('store_id',$allow)->update($param);
            }else{
                $param['store_id'] = $allow;
                $data = db('logistics_sender')->insert($param);
            }

            return api_json_echo(true,'成功','',200);
        }
        //对应店铺发货信息
        $data = db('logistics_sender')->where('store_id',$allow)->find();
        //物流公司信息
        $logistics = db('logistics')->select();
        $this->assign('logistics',$logistics);
        $this->assign('data', isset($data)?$data:['code'=>'','name'=>'','mobile'=>'','province_name'=>'','city_name'=>'','exp_area_name'=>'','address'=>''] );
        return $this->fetch('logistics_order/logisticsConfig');
    }
    /**
     * 订单物流管理
     */
    public function logisticsOrder(){
        $param = $this->request->param();
        $pagesize = !empty($param['pagesize']) ? $param['pagesize'] : 20;//页面条数
        $page = !empty($param['page']) ? $param['page'] : 1;//当前页数
        
        $allow = $this->com->getAllowAccess();
        if($allow == 'true') $allow = 'admin';
        $param['store_id'] = $allow ;
        /*快递公司列表 */
        $logistics = db('logistics')->select();
        /*读取默认快递公司*/
        $code = db('logistics_sender')->where('store_id',$allow)->find()['code'];
        $where['store_id'] = ["=",$allow];
        if(!empty($param['title'])){
            $title = $param['title'];
            
            if( $param['kind'] == '1' ) {
                $where['order_num'] = ["like","%".$title."%"];
            }
            if( $param['kind'] == '2' ){
                $where['logistics_code'] = ["like","%".$title."%"];
            }
            if( $param['kind'] == '3' ){
                $where['mobile'] = ["like","%".$title."%"];
            }
        }else{
            $param['title']='';
            $param['kind']='';
        }
        if( !empty( $param['start_time'] ) ) {
            $where['delivery_time'] = ['>=',strtotime($param['start_time'])];
        }else{
            $param['start_time']='';
        }
        if( !empty( $param['end_time'] ) ) {
            $where['delivery_time'] = ['<=',strtotime($param['end_time'])];
        }else{
            $param['end_time']='';
        }
        if( !empty($param['status']) ) {
            $where['status'] = ['=',$param['status']];
        }else{
            $param['status']='';
        }
        if( !empty($param['type']) ) {
            $where['type'] = ['=',$param['type']];
        }else{
            $param['type']='';
        }
        if( !empty($param['code']) ){
             $where['code'] = ['=',$param['code']];
        }else{
            $param['code']='';
        }
        $sear = $param ;
        $sear['pagesize'] = $pagesize;
        //搜索
        $data = db('logistics_order')
                ->where($where)
                ->order('status asc,delivery_time desc')
                ->paginates($pagesize, false ,['query'=>$sear]);
        //快递公司列表

        $data->appends($param);
        $this->assign('page',$data->render());
        $this->assign('data',$data);
        $this->assign('logistics',$logistics);
        $this->assign('code',isset($code['code'])?$code['code']:'');
        $this->assign('param',$param);
        return $this->fetch('logistics_order/logisticsOrder');
    }
    /**
     * 收货信息修改
     */
    public function ordereditPage()
    {
        $id = $this->request->param('id');

        if( $this->request->isPost() ) {
            $data  = $this->request->post();
            $res = db('logistics_order')->where('order_num',$data['order_num'])->update($data);
            return api_json_echo(true,'成功','',200);
        }

        $data = db('logistics_order')->where('id',$id)->find();
        $this->assign('data',$data);
        return $this->fetch('logistics_order/ordereditPage');
    }
    /*
      * 订单报表导出
      */
      public function exmodel () {

        require_once 'classes/phpexcel/PHPExcel.php';
        //实例化
        $objPHPExcel = new \PHPExcel();
        /*右键属性所显示的信息*/
        $objPHPExcel->getProperties()->setCreator("cy")  //作者
        ->setLastModifiedBy("cy")  //最后一次保存者
        ->setTitle('数据EXCEL导出')  //标题
        ->setSubject('数据EXCEL导出') //主题
        ->setDescription('导出数据')  //描述
        ->setKeywords("excel")   //标记
        ->setCategory("result file");  //类别
        $objPHPExcel->getActiveSheet()->setTitle('Simple');
        //设置当前的表格
        $objPHPExcel->setActiveSheetIndex(0);
        // 设置表格第一行显示内容
        $objPHPExcel->getActiveSheet()
            ->setCellValue('A1', 'id')
            ->setCellValue('B1', '订单编号')
            ->setCellValue('C1', '收货人')
            ->setCellValue('D1', '收货地址')
            ->setCellValue('E1', '收货联系方式')
            ->setCellValue('F1', '购买商品')
            ->setCellValue('G1', '备注')
            ->setCellValue('H1', '物流公司')
            ->setCellValue('I1', '物流单号')
            // ->setCellValue('J1', '')
            //设置第一行为红色字体
            ->getStyle('I1')->getFont()->getColor()->setARGB(\PHPExcel_Style_Color::COLOR_RED);
        $objPHPExcel->getActiveSheet()->setTitle('发货订单');
        $key = 1;
        /*以下就是对处理Excel里的数据，横着取数据*/
        //$arr = [['1','0','第一个栏目']];

        $allow = $this->com->getAllowAccess();
        if($allow == 'true') $allow = 'admin';
        $map['store_id'] =['=', $allow ];
        if ( !empty(input('start_time')) ) {
            $map['delivery_time']  = ['>=',strtotime( input('start_time'))];
        }

        if ( !empty(input('end_time')) ) {
            $map['delivery_time']  = ['<=',strtotime( input('end_time') )];
        }
        if( !empty(input('start_time')) && !empty(input('end_time'))){
            $map['delivery_time']  = [['>=',strtotime( input('start_time'))],['<=',strtotime( input('end_time') )],'AND'];
        }
        if (!empty(input('status'))) {
            $map['status']  = ['=',input('status')];
        }
        if (!empty(input('code'))) {
            $map['code']  = ['=',input('code')];
        }
        if( input('type') !== '2'){
            return  '只有线下可导出' ;
        }else{
            $map['type']  = ['=',input('type')];
        }

        $arr = db('logistics_order')->where($map)->select();

        foreach($arr as $v){
            //设置循环从第二行开始
            $key++;
            $objPHPExcel->getActiveSheet()
                //Excel的第A列，name是你查出数组的键值字段，下面以此类推
                ->setCellValue('A'.$key, $v['id'])
                ->setCellValue('B'.$key, $v['order_num'])
                ->setCellValue('C'.$key, $v['name'])
                ->setCellValue('D'.$key, $v['province'].$v['city'].$v['area'].$v['address'])
                ->setCellValue('E'.$key, $v['mobile'])
                ->setCellValue('F'.$key, $v['goods'])
                ->setCellValue('G'.$key, $v['remarks'])
                ->setCellValue('H'.$key, $v['company'])
                ->setCellValue('I'.$key, $v['logistics_code']);
                // ->setCellValue('J'.$key, '');
        }

        //设置当前的表格

        $name = '发货订单';
        $objPHPExcel->setActiveSheetIndex(0);
        ob_end_clean();  //清除缓冲区,避免乱码
        header('Content-Type: application/vnd.ms-excel'); //文件类型
        header('Content-Disposition: attachment;filename="'.$name.'.xls"'); //文件名
        header('Cache-Control: max-age=0');
        header('Content-Type: text/html; charset=utf-8'); //编码

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');  //excel 2003
        $objWriter->save('php://output');
        exit;
    }
    /**
     * 批量发货列表
     */
    public function deliveryList()
    {
        //店铺id
        $allow = $this->com->getAllowAccess();
        if($allow == 'true') $allow = 'admin';
        $order_num = $this->request->param('order_num');
        $order_num = explode(',',$order_num);
        $order_num = array_merge(array_diff($order_num, [0=>"on"]));

        //默认物流配置
        $sender = db('logistics_sender')->where('store_id',$allow)->find();

        //物流公司
        $compary = db('logistics')->where('code',$sender['code'])->find()['company'];
        //自动填充物流单号
        $logistics_code = db('logistics_library')->where(['code'=>$sender['code'],'status'=>1])->select();
        //发货列表 显示选中的待发货订单
        $data = db('logistics_order')->where('order_num','in', $order_num)->where('status',1)->select();
        if( $sender['mode'] == 2 )
        {//线下
            //缓存数据
            $cache =[
                $sender['code']=> [],
            ];
            foreach($data as $key => $value )
            {//物流单号库填充
                if(empty($logistics_code[$key])){
                    $value['logistics_code'] = '';
                }else{
                    $value['logistics_code'] = $logistics_code[$key]['logistics_code'];
                }
                if(!empty($logistics_code[$key])){
                    //向缓存数据添[订单编号=>物流编号]
                    $cache[$sender['code']][$value['order_num']] = $logistics_code[$key]['logistics_code'];
                }
                //向缓存数据添[订单编号=>物流编号]
                // $cache[$sender['code']][$value['order_num']] = !empty($logistics_code[$key]['logistics_code'])?$logistics_code[$key]['logistics_code']:'';
                $data[$key] = $value;
            }
            //设置当前占用缓存
            Cache($allow,$cache);
        }elseif( $sender['mode'] == 1 )
        {//线上
            foreach( $data as $key =>$value ){
            $admin = new \plugins\logistics\controller\AdminIndexController;
            //寄件地址信息
            $senderInfo = ["Name"=>$sender['name'],"Mobile"=>$sender['mobile'],"ProvinceName"=>$sender['province_name'],"CityName"=>$sender['city_name'],"ExpAreaName"=>$sender['exp_area_name'],"Address"=>$sender['address']];
            //收件地址信息
            $receiver = ["Name"=>$value['name'],"Mobile"=>$value['mobile'],"ProvinceName"=>$value['province'],"CityName"=>$value['city'],"ExpAreaName"=>$value['area'],"Address"=>$value['address']];
//            $res = $admin->placeOrder($sender['code'],$value['order_num'], $senderInfo,$receiver);
            //面单成功
//            if(!empty($res['Success'] == 'true'))
//            {//跟新订单发货
//                db('logistics_order')->where('order_num',$value['order_num'])->update(['logistics_code'=>$res['Order']['LogisticCode'],'code'=>$sender['code'],'status'=>3,'delivery_time'=>time(),'compary'=>$compary,'type'=>1]);
//            }
//                $value['logistics_code'] = isset($res['Order']['LogisticCode']) ? $res['Order']['LogisticCode']:'';
                $value['logistics_code'] = '';
                $data[$key] = $value;
            }
        }
        //物流公司信息
        $logistics = db('logistics')->select();
        $this->assign('logistics',$logistics);
        $this->assign('mode',$sender['mode']);
        $this->assign('company',$sender['code']);
        $this->assign('data',$data);
        return $this->fetch('logistics_order/deliveryList');
    }
    /**
     * 发货列表修改物流公司物流单号
     */
    public function logisticsCode()
    {
        //店铺id
        $allow = $this->com->getAllowAccess();
        if($allow == 'true') $allow = 'admin';
        $cache = Cache($allow);//获取缓存数据

        $param = $this->request->post();
        $code = $param['code'];
        $order_num = $param['order_num'];
        if($cache){
            foreach( $cache as $key => $value){
                //是否存在此订单编号
                if(in_array($order_num,array_keys($value))){
                    unset($cache[$key][$order_num]);//存在去除
                }
            }
        }

        $notIn = "";
        if( isset( $cache[$code] ) ){
            $notIn = array_values( $cache[$code] );//选中物流公司下已存缓存中的 物流单号
        }
        $res = db('logistics_library')
        ->where(['code'=>$code,'status'=>1,'store_id'=>$allow])
        ->where( 'logistics_code' , 'not in' , $notIn )
        ->find()['logistics_code'];
        $cache[$code][$order_num] = $res;
        cache($allow, $cache);//设置缓存数据
        return api_json_echo(true,'成功',$res,200);
    }
    /**
     * 保存发货列表物流单号
     */
    public function preserveLogistics()
    {
        //店铺id
        $allow = $this->com->getAllowAccess();
        if($allow == 'true') $allow = 'admin';
        //选择的发货列表
        $data = $this->request->post();
        
        foreach($data['logistics_code'] as $code => $co){
            if(empty($co)) return api_json_echo(false,'物流单号必填');
        }
        $info= array();
        foreach ($data as $key => $value) {
       
            foreach($value as $ke => $val){
                $info[$ke][$key] = $val ;
            }
        }

       
        foreach($info as $in){
        //物流公司
        $company = db('logistics')->where('code',$in['code'])->find()['company'];
        //保存物流单号公司信息更改状态发货时间
        $res = db('logistics_order')->where(['id'=>$in['id'],'order_num'=>$in['order_num']])->update(['status'=>3,'logistics_code'=>$in['logistics_code'],'code'=>$in['code'],'delivery_time'=>time(),'company'=>$company,'type'=>2]);
        //变更快递单号库内单号状态填充订单编号
        $res = db('logistics_library')->where(['code'=>$in['code'],'logistics_code'=>$in['logistics_code']])->update(['status'=>2,'order_num'=>$in['order_num']]);
        }
        cache($allow, NULL);//删除缓存数据
        return api_json_echo(true,'成功','',200);
    }
    /**
     * 快递单号库
     */
    public function library()
    {
        $param = $this->request->param();
        //店铺id
        $allow = $this->com->getAllowAccess();
        if($allow == 'true') $allow = 'admin';
        $where = ['store_id'=>$allow];
        $search = empty($param['search']) ? '' : $param['search'];
        if(!empty($search['title'])){
            $title = $search['title'];
            if( $search['type'] == '1' ) $where['order_num'] = $title;
            if( $search['type'] == '2' ) $where['logistics_code'] = $title;
        }
        if( !empty( $search['status'] ) ) $where['status'] = $search['status'];
        if( !empty( $search['code'] ) ) $where['code'] = $search['code'];
        $data = db('logistics_library')->where($where)->select();
        $logistics = db('logistics')->select();
        $this->assign('search',empty($search) ? ['type'=>'','title'=>'','order_num'=>'','status'=>'','code'=>'']:$search);
        $this->assign('data',$data);
        $this->assign('logistics',$logistics);
        return $this->fetch('logistics_order/library');
    }
    /**
     * 单号库录入快递单号
     */
    public function addLogisticsOrder()
    {
        //店铺id
        $allow = $this->com->getAllowAccess();
        if($allow == 'true') $allow = 'admin';
        $param = $this->request->post();
        $setting = [
            'num'=>['type'=>'require','message'=>['require'=>'物流单号必填']]
        ];
        // 验证参数
        checkParam($setting,$param);
        $data = [];
        $code = $param['code'];
        $num = explode(',',$param['num']);//录入单号内容逗号打散
        $mag ='';//返回提醒内容
        foreach($num as $key => $value){

            $val = explode('-',$value);//连号 - 大撒
            if(count($val)>1){//是连号
                for($i=$val[0]; $i<=$val[1]; $i++){
                    if(db('logistics_library')->where(['code'=>$code,'logistics_code'=>$i])->find()){
                        $mag .= $i.'、';
                    }else{
                      $data[] = ['code'=>$code,
                               'logistics_code'=>$i,
                               'store_id'=>$allow,
                              ];
                    }

                }
            }else{//
                if(db('logistics_library')->where(['code'=>$code,'logistics_code'=>$value])->find()){
                    $mag .= $value.'、';
                }else{
                  $data[] = ['code'=>$code,
                           'logistics_code'=>$value,
                           'store_id'=>$allow,
                          ];
                }
            }
        }

        $res = db('logistics_library')->insertAll($data);
        if(!empty($mag)) {$mag .='已存在不可重复';}
        $logistics = db('logistics')->select();
        $this->assign('logistics',$logistics);
        return api_json_echo(true ,'成功'.$mag,'',200);
    }
    /**
     * 编辑单号库
     */
    public function editLogisticsOrder()
    {
        $param = $this->request->param();
        if($this->request->isPost()){
            $param = $this->request->post();
            if($param['status'] == 2 && empty($param['order_num']))
            return api_json_echo(false,'已使用状态下必须填写订单编号','',100);
            $data = db('logistics_library')->where(['code'=>$param['code'],'logistics_code'=>$param['logistics_code']])->find();
            if($data['id'] !== $param['id']) return api_json_echo(false,'不可重复','',100);

            $res = db('logistics_library')->update($param);

            return api_json_echo(true,'成功','',200);
        }
        $data = db('logistics_library')->where('id',$param['id'])->find();
        $logistics = db('logistics')->select();
        $this->assign('logistics',$logistics);
        $this->assign('data',$data);
        return $this->fetch('logistics_order/editLogisticsOrder');
    }
    /**
     * 快递单号库删除
     */
    public function delete()
    {
        $id = $this->request->param('id');
         db('logistics_library')->where('id',$id)->delete();
        return api_json_echo(true,'成功','',200);
    }
    /**
     * 配置寄件信息
     */
    public function senderPage()
    {
        $allow = $this->com->getAllowAccess();
        if($allow == 'true') $allow = 'admin';
        if($this->request->isPost()) {
            $data = $this->request->post();
            $data['store_id'] = $allow;
            if(db('logistics_sender')->where('store_id',$allow)->find()) {
                db('logistics_sender')->where('store_id',$allow)->update($data);
            }else{
                db('logistics_sender')->where('store_id',$allow)->insert($data);
            }

            return api_json_echo(true ,'成功','',200);
        }
        $data = db('logistics_sender')->where('store_id',$allow)->find();
        $this->assign('data',$data);
        return $this->fetch('admin_index/senderPage');
    }
    /**
     * 设默认快递公司
     */
    public function setCode()
    {
        $data = $this->request->post();
        $allow = $this->com->getAllowAccess();
        if($allow == 'true') $allow = 'admin';

        if(db('logistics_sender')->where('store_id',$allow)->find()) {
            db('logistics_sender')->where('store_id',$allow)->update($data);
        }else{
            db('logistics_sender')->where('store_id',$allow)->insert($data);
        }

        return api_json_echo(true ,'成功','',200);
    }
    /**
     * 批量面单
     */
    public function generate()
    {
        $param = $this->request->post();
        $data = db('logistics_order')->where('id','in',$param['id'])->field('order_num,code,')->select();
        foreach ($data as $key =>$value){
           $receiver = db('order_consignee')->where('order_num',$value['order_num'])->field('order_consignee_name,order_consignee_phone,order_consignee_address')->find();
           //收件信息
           $info = $this->handleAddress($receiver['order_consignee_address']);
           $info['Name'] = $receiver['order_consignee_name'];
           $info['Mobile'] = $receiver['order_consignee_phone'];
           $value['receiver'] = $info;
           $value['GoodsName'] = db('order_goods_list')->where('order_num')->find()['order_goods_name'];
        }
        return api_json_echo(true,'删除','',200);
    }

    /**
     * 拆分详细地址
     */

     function handleAddress($address ='广东省深圳市龙华新区大浪街道同胜科技大厦')
     {
        preg_match('/(.*?(省|自治区|北京市|天津市))/',$address,$matches);
        if( count($matches) > 1) {
            $province = $matches[count($matches) - 2];
            $address = str_replace($province,'',$address);
        }
        preg_match('/(.*?(市|自治州|地区|区划|县))/',$address,$matches);
        if( count($matches) > 1) {
            $city = $matches[count($matches) - 2];
            $address=str_replace($city,'',$address);
        }
        preg_match('/(.*?(区|县|镇|乡|街道))/',$address,$matches);
        if( count($matches) > 1) {
            $area = $matches[count($matches) - 2];
            $address = str_replace($area,'',$address);
        }
        return[
            'ProvinceName'=>isset($province)?$province:'',
            'CityName'=>isset($city)?$city:'',
            'ExpAreaName'=>isset($area)?$area:'',
            'Address'=>$address
        ];}
}